#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/9 22:46
# @USER    : Shengji He
# @File    : NextPermutation.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from typing import List


class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.

        Implement next permutation, which rearranges numbers into the lexicographically next greater permutation
        of numbers.

        If such arrangement is not possible, it must rearrange it as the lowest possible order
        (ie, sorted in ascending order).

        The replacement must be in-place and use only constant extra memory.

        Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the
        right-hand column.

        1,2,3 → 1,3,2

        3,2,1 → 1,2,3

        1,1,5 → 1,5,1

        :param nums: List[int]
        """
        # left = -1
        # for i in range(len(nums) - 1, 0, -1):
        #     if nums[i] > nums[i - 1]:
        #         left = i - 1
        #         break
        # if left == -1:
        #     nums.reverse()
        # else:
        #     right = len(nums) - 1
        #     for i in range(left + 1, len(nums)):
        #         if nums[left] >= nums[i]:
        #             right = i - 1
        #             break
        #
        #     nums[left], nums[right] = nums[right], nums[left]
        #     n = len(nums)
        #     while left + 1 < n - 1:
        #         nums[left + 1], nums[n - 1] = nums[n - 1], nums[left + 1]
        #         left += 1
        #         n -= 1
        for i in range(len(nums)-1, 0, -1):
            if nums[i] > nums[i-1]:
                nums[i:] = sorted(nums[i:])
                for j in range(i, len(nums)):
                    if nums[j] > nums[i-1]:
                        nums[j], nums[i-1] = nums[i-1], nums[j]
                        break
                return
        nums.sort()



if __name__ == '__main__':
    S = Solution()
    # nums = [4,2,0,2,3,2,0]
    nums = [2,2,7,5,4,3,2,2,1]
    # nums = [4, 6, 5, 3, 2, 1]
    # nums = [1,2, 3, 4, 6, 5]
    # nums = [1,2,4,3]
    # nums = [1, 1, 5]
    # nums = [3, 2, 1]
    # nums = [2, 3, 1]
    # nums = [1, 2, 3]
    # nums = [1, 2]
    S.nextPermutation(nums)
    print('done')
